package com.jrwd.recycletest;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.ProgressDialog;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.net.http.SslError;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.text.ClipboardManager;
import android.text.TextUtils;
import android.view.View;
import android.webkit.DownloadListener;
import android.webkit.JavascriptInterface;
import android.webkit.SslErrorHandler;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.LinearLayout;

import com.alibaba.fastjson.JSONObject;
import com.jrwd.recycletest.mange.UserCache;
import com.jrwd.recycletest.util.CacheUtil;
import com.jrwd.recycletest.util.QTLog;
import com.jrwd.recycletest.util.VersionUtil;

import java.io.File;
import java.lang.ref.WeakReference;
import java.net.URLDecoder;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Created by KK on 16/6/12.
 */
public class WebViewAct extends BaseAct {

    @BindView(R.id.iv_cross)
    ImageView ivCross;
    @BindView(R.id.tip_layout)
    LinearLayout tipLayout;
    private WebView mWebView;


    private ProgressDialog progressDialog;

    private boolean isFirst = true;
    private boolean isPause = true;


    private int second = 0;


    private TimeHandler timeHandler = new TimeHandler(this);
    private File file;

    static class TimeHandler extends Handler {

        WeakReference<WebViewAct> weakReference;

        public TimeHandler(WebViewAct activity){
            weakReference = new WeakReference<>(activity);
        }

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            final WebViewAct activity = weakReference.get();
            if(activity != null){
                if(msg.what == 0){
                    QTLog.e("-------------"+activity.second);

                }
            }
        }
    }
    /**
     * 获取存储权限
     */
    private boolean getStoragePermissions() {

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 101);
                return false;
            }
        }
        return true;
    }

    private void downApk(String url, final String fileName) {

        progressDialog = new ProgressDialog(mContext);
        progressDialog.setTitle("正在下载");
        progressDialog.setMessage("请稍候...");
        progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        progressDialog.setCancelable(false);
        OkHttpUtil.downFile(WebViewAct.this, url, fileName, new OkHttpUtil.ProgressListener() {
            @Override
            public void update(final long bytesRead,final long contentLength,final boolean done) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        progressDialog.setProgress((int) (bytesRead*100/contentLength));
                        if(done) {
                            progressDialog.dismiss();
                            File directory= Environment.getExternalStorageDirectory();
                             file = new File(directory,fileName);

                            VersionUtil.installAPK(WebViewAct.this, file);
                            if ( mWebView.canGoBack()){
                                mWebView.goBack();
                            }

                        }
                    }
                });
            }
        },progressDialog);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case 123:
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    VersionUtil.installAPK(WebViewAct.this, file);
                } else {
                    Intent intent = new Intent(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES);
                    startActivityForResult(intent, 123);
                }
                break;

        }
    }
    @Override
    public int setContentView(Bundle savedInstanceState) {
        return R.layout.a_webview;

    }

    @Override
    public void initView() {
        cacheUtil = CacheUtil.get(WebViewAct.this);
        mWebView =findViewById(R.id.mWebView);
        DialogUtils.showLoadingDialog(mContext);
        initWebView();
        mWebView.loadUrl("https://www.hao123.com/");

    }

    @SuppressLint("JavascriptInterface")
    private void initWebView() {
        WebSettings settings = mWebView.getSettings();
        settings.setJavaScriptEnabled(true);
        settings.setDomStorageEnabled(true);
        settings.setUseWideViewPort(true);
        settings.setLoadWithOverviewMode(true);
        settings.setCacheMode(WebSettings.LOAD_NO_CACHE);
        settings.setAllowContentAccess(true); // 是否可访问Content Provider的资源，默认值 true
        settings.setAllowFileAccess(true);    // 是否可访问本地文件，默认值 true
        settings.setUserAgentString(settings.getUserAgentString() + "JHH_Android");
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            settings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.TEXT_AUTOSIZING);
        } else {
            settings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NORMAL);
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            settings.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
        }
        mWebView.setWebViewClient(new MyClient());
        mWebView.setWebChromeClient(new MyChromeClient());
        mWebView.setDownloadListener(new MyWebViewDownLoad());

        mWebView.addJavascriptInterface(new JsAndroid(), "jhh_control");
    }

    public class JsAndroid {

        @JavascriptInterface
        public void copyText(String message) {
            // 从API11开始android推荐使用android.content.ClipboardManager
            // 为了兼容低版本我们这里使用旧版的android.text.ClipboardManager，虽然提示deprecated，但不影响使用。
            ClipboardManager cm = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
            // 将文本内容放到系统剪贴板里。
            cm.setText(message);
        }

        @JavascriptInterface
        public String sendMsg() {

            JSONObject json = new JSONObject();
            if (!TextUtils.isEmpty(UserCache.getMobile(WebViewAct.this)) &&
                    !TextUtils.isEmpty(UserCache.getSign(WebViewAct.this))) {
                json.put("mobile", UserCache.getMobile(WebViewAct.this));
                json.put("sign", UserCache.getSign(WebViewAct.this));
            }
            return json.toJSONString();
        }
    }
    @OnClick(R.id.iv_cross)
    public void onClick() {
        tipLayout.setVisibility(View.GONE);
    }


    private class MyChromeClient extends WebChromeClient {

        @Override
        public void onReceivedTitle(WebView view, String title) {
            super.onReceivedTitle(view, title);
        }

        @Override
        public void onProgressChanged(WebView view, int newProgress) {
            if (newProgress == 100) {
              DialogUtils.dismiss();

            }
            super.onProgressChanged(view, newProgress);
        }

    }

    private class MyWebViewDownLoad implements DownloadListener {
        String fileName;

        @Override
        public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype, long contentLength) {
            if(!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
                DialogUtils.showCommonDialog(WebViewAct.this,"温馨提示","请检查您的SD卡",null,null,null);
                return;
            }
            fileName=url.substring(url.lastIndexOf("/")+1);
            fileName= URLDecoder.decode(fileName);
            if (getStoragePermissions()){
                if (Build.VERSION.SDK_INT >= 26) {
                    boolean b = getPackageManager().canRequestPackageInstalls();
                    if (!b) {
                        ActivityCompat.requestPermissions(WebViewAct.this, new String[]{Manifest.permission.REQUEST_INSTALL_PACKAGES}, 123);
                        if ( mWebView.canGoBack()){
                            mWebView.goBack();

                        }
                    }else {
                        downApk(url,fileName);
                    }
                } else {
                    downApk(url,fileName);
                }

            }
        }
    }

    private class MyClient extends WebViewClient {
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            if (url == null)
                return false;
            if(url.startsWith("https") || url.startsWith("http")){
                if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){
                    return false;
                }else {
                    view.loadUrl(url);
                }

            }else if (url.startsWith("tel:")) {
                //调用拨号程序
                Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
                startActivity(intent);
                return true;
            }else{
                //不管是什么自定义的协议，只要安装有协议所属的app，都可以打开对应的app，
                //如果没有安装app则会打开相应的web网页
                try {
                    Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
                    startActivity(intent);
                } catch (ActivityNotFoundException e) {
                    e.printStackTrace();
                }
                return true;
            }
            return super.shouldOverrideUrlLoading(view, url);
        }

        @Override
        public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
            // TODO Auto-generated method stub
            super.onReceivedError(view, errorCode, description, failingUrl);

            String data = "网络异常！";
            view.loadUrl("javascript:document.body.innerHTML=\"" + data + "\"");
        }
        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);

            if (!TextUtils.isEmpty(UserCache.getMobile(WebViewAct.this)) &&
                    !TextUtils.isEmpty(UserCache.getSign(WebViewAct.this))) {
                mWebView.loadUrl("javascript:getUserInfo('" + UserCache.getMobile(WebViewAct.this) +
                        "','" + UserCache.getSign(WebViewAct.this) + "')");
            }

        }

        @Override
        public void doUpdateVisitedHistory(WebView view, String url, boolean isReload) {
            super.doUpdateVisitedHistory(view, url, isReload);
//            if (dose == 1) {
//                view.clearHistory();
//            }
        }

        @Override
        public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
            handler.proceed();
        }
    }


    @Override
    public void onResume() {
        super.onResume();
        mWebView.onResume();
        QTLog.e("-------------onResume-------"+second);
    }

    @Override
    public void onPause() {
        super.onPause();
        mWebView.onPause();
        QTLog.e("-------------onPause-------"+second);

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        if (DialogUtils.dialog!=null){
            DialogUtils.dismiss();
        }
        mWebView.destroy();
        timeHandler.removeCallbacksAndMessages(null);
    }

    @Override
    public void onBackPressed() {

       if ( mWebView.canGoBack()){
           mWebView.goBack();

       }else {
           super.onBackPressed();
       }


    }
}